package com.fanshuai2.test;

import java.util.Arrays;
import java.util.Collections;

/**
 * 非负整数  数组排列  组成最大的数字
 */
public class NumStringSort {

    static String largestNum(int[] arr) {
        String[] s = new String[arr.length];

        int i = 0;
        for (int a: arr) {
            s[i] = String.valueOf(a);
            i++;
        }

        /**
         * s2 > s1
         *
         * 30 < 3
         * 34 > 3
         * 334 > 3
         * 330 < 3
         *
         * s2 < s1
         *
         * 3 > 30
         * 3 < 34
         * 3 > 330
         * 3 < 334
         */
        Arrays.sort(s, (s1, s2) -> {
            int comp = s1.compareTo(s2);
            if (comp == 0) {
                return comp;
            } else  {
                int j = 0; int k = 0;
                while (j < s1.length() && k < s2.length()) {
                    if (s1.charAt(j) == s2.charAt(k)) {
                        j++;
                        k++;
                    } else if (s1.charAt(j) > s2.charAt(k)) {
                        return -1;
                    } else {
                        return 1;
                    }
                }

                if (j < s1.length() || k < s2.length()) {
                    if (k == s2.length()) {
                        while (j < s1.length()) {
                            if (s1.charAt(j) < s2.charAt(k - 1)) {
                                return 1;
                            } else if (s1.charAt(j) == s2.charAt(k - 1)) {
                                j++;
                            } else {
                                return -1;
                            }
                        }
                    }
                    if (j == s1.length()) {
                        while (k < s2.length()) {
                            if (s1.charAt(j - 1) < s2.charAt(k)) {
                                return 1;
                            } else if (s1.charAt(j - 1) == s2.charAt(k)) {
                                k++;
                            } else {
                                return -1;
                            }
                        }
                    }
                }
            }
            return -comp;
        });

        StringBuilder b = new StringBuilder();
        for (String each: s) {
            b.append(each);
        }
        return b.toString();
    }

     public static void main(String[] args) {
        int[] arr1 = new int [] {10, 2};
        int[] arr2 = new int[] {3, 30, 34, 5, 9};

        System.out.println(largestNum(arr1));
        System.out.println(largestNum(arr2));
     }
}
